//
//  HJSelectFile.m
//  KaiChat
//
//  Created by lx on 2023/10/25.
//

#import "HJSelectFile.h"
#import <Photos/Photos.h>
#import <PhotosUI/PhotosUI.h>
#import <MobileCoreServices/MobileCoreServices.h>

//#if __IPHONE_OS_VERSION_MIN_REQUIRED >= __IPHONE_14_0

@interface HJSelectFile()<PHPickerViewControllerDelegate, UINavigationControllerDelegate, UIImagePickerControllerDelegate>


@property (nonatomic, strong) dispatch_queue_t queue;
@property (nonatomic, strong) dispatch_group_t group;
@property (nonatomic, copy) void (^selectPhotoComplete)(NSArray<UIImage *> *photos,NSArray *fileUrls);
@property (nonatomic, copy) void (^openCameraComplete)(NSString *localPath, NSString *classFile, UIImage *image);


@end


@implementation HJSelectFile

- (instancetype)init {
    if (self = [super init]) {
        _queue = dispatch_queue_create("SELECTFILEQUEUE", DISPATCH_QUEUE_CONCURRENT);
        _group = dispatch_group_create();
    }
    return self;
}


- (void)openPicturesInController:(UIViewController *)controller complete:(void (^)(NSString *localPath, NSString *classFile, UIImage *image))complete {
    
    
}

- (void)selectPhotoInController:(UIViewController *)controller complete:(void (^)(NSArray<UIImage *> *photos,NSArray *fileUrls))complete {
    self.selectPhotoComplete = complete;
    if (@available(iOS 14, *)) {
        PHPickerConfiguration *configuration = [[PHPickerConfiguration alloc] init];
        configuration.filter = [PHPickerFilter imagesFilter];
        configuration.selectionLimit = 10;
        PHPickerViewController *picker = [[PHPickerViewController alloc] initWithConfiguration:configuration];
        picker.delegate = self;
        picker.modalPresentationStyle = UIModalPresentationFullScreen;
        [controller presentViewController:picker animated:YES completion:nil];
        [HJTools tool].imagePickerController = picker;
    } else {
        
        
    }
    
}

- (void)picker:(PHPickerViewController *)picker didFinishPicking:(NSArray<PHPickerResult *> *)results  API_AVAILABLE(ios(14)){
    
    TJWeakify(self)

    [picker dismissViewControllerAnimated:YES completion:nil];
    
    NSMutableArray *photos = [NSMutableArray array];
    NSMutableArray *URLs = [NSMutableArray array];

    for (PHPickerResult *result in results) {
        NSItemProvider *itemProvider = result.itemProvider;
        if ([itemProvider canLoadObjectOfClass:[UIImage class]]) {
            dispatch_group_enter(weakself.group);
            dispatch_group_async(weakself.group, weakself.queue, ^{
                [result.itemProvider loadFileRepresentationForTypeIdentifier:@"public.image" completionHandler:^(NSURL *fileURL, NSError *error) {
                    if (!error) {
                        UIImage *image = [UIImage imageWithContentsOfFile:fileURL.path];
                        [photos addObject:image];
                        [URLs addObject:fileURL];
                        dispatch_group_leave(weakself.group);
                    }
                }];
            });
        }
    }
    
    dispatch_group_notify(self.group, dispatch_get_main_queue(), ^{
        if (photos.count == 0) {
        } else {
            self.selectPhotoComplete(photos, URLs);
        }
    });
    
}

- (void)openCameraInController:(UIViewController *)controller complete:(void (^)(NSString *localPath, NSString *classFile, UIImage *image))complete {
    
    
    self.openCameraComplete = complete;
    
    if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        NSLog(@"sorry, no camera or camera is unavailable.");
        return;
    }
    
    UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
    imagePickerController.delegate = self;
    imagePickerController.modalPresentationStyle = UIModalPresentationFullScreen;
    imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
    imagePickerController.videoMaximumDuration = 15;
    imagePickerController.mediaTypes = @[(NSString *)kUTTypeImage, (NSString *)kUTTypeMovie];
    imagePickerController.videoQuality = UIImagePickerControllerQualityTypeHigh;
    imagePickerController.cameraCaptureMode = UIImagePickerControllerCameraCaptureModePhoto;
    imagePickerController.allowsEditing = NO;
    imagePickerController.cameraDevice = UIImagePickerControllerCameraDeviceRear;
    imagePickerController.cameraFlashMode = UIImagePickerControllerCameraFlashModeAuto;
    [controller presentViewController:imagePickerController animated:YES completion:nil];
}


- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
        
    if (!_openCameraComplete) {
        return;
    }
    
    NSString* mediaType = [info objectForKey:UIImagePickerControllerMediaType];

    if ([mediaType isEqualToString:(NSString *)kUTTypeImage]) {
        //生成图片的名字
        UIImage *originalImage = [info objectForKey:UIImagePickerControllerOriginalImage];
 
        NSString *localPath = nil;
        BOOL result = NO;
            localPath = getFileNameWithPathExtension(@"jpg").tj_IMFileCachePath;
            result = [HJTools writeIMImage:originalImage toLocalPath:localPath];
        
        UIImage *thumbnailImage = [UIImage imageWithData:[UIImage lubanCompressImage:originalImage]];
        [picker dismissToRootViewController:YES completion:^{
            if (result) {
                self.openCameraComplete(localPath, @"image", thumbnailImage);
            } else {
                self.openCameraComplete(nil, @"image", thumbnailImage);
            }
        }];
        return;
    }
    
    if ([mediaType isEqualToString:(NSString *)kUTTypeMovie]) {
            
        NSURL* mediaURL = [info objectForKey:UIImagePickerControllerMediaURL];
        NSString *localPath = getFileNameWithPathExtension(mediaURL.pathExtension).tj_IMFileCachePath;
       
        NSError *error = nil;
        NSURL *localUrl = [NSURL fileURLWithPath:localPath];
        BOOL result = [[NSFileManager defaultManager] copyItemAtURL:mediaURL toURL:localUrl error:&error];
        UIImage *thumbnailImage = [HJTools getVideoFirstViewImageWithURL:localUrl];
        [picker dismissToRootViewController:YES completion:^{
            if (result) {
                self.openCameraComplete(localPath, @"video", thumbnailImage);
            } else {
                self.openCameraComplete(nil, @"video", thumbnailImage);
            }
        }];
 
    }
    
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    [picker dismissToRootViewController:YES completion:nil];
    
}

@end
